package demo.android.com.myhttpdemo.http;

import android.content.Context;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * description:
 * author: Darren on 2017/8/21 11:36
 * email: 240336124@qq.com
 * version: 1.0
 */
public class ConnectUtils {
    private IHttpRequest mHttpRequest;
    private static IHttpRequest mInitHttpRequest;
    private final int TYPE_POST = 0x0011,TYPE_GET = 0x0022;
    private int mType = TYPE_GET;
    private Map<String,Object> mParams;
    private String mUrl;
    private boolean cache;
    private Context mContext;
    // 指定配置 config 参数
    static EngineConfig mConfig;

    public static ConnectUtils with(Context context){
        return new ConnectUtils(context);
    }

    public ConnectUtils httpRequest(IHttpRequest httpRequest){
        mHttpRequest = httpRequest;
        return this;
    }

    public ConnectUtils get(){
        mType = TYPE_GET;
        return this;
    }

    private ConnectUtils(Context context) {
        mParams = new HashMap<>();
        this.mContext = context;
    }

    public static void initConfig(EngineConfig engineConfig) {
        mConfig = engineConfig;
        mInitHttpRequest = mConfig.getEngineRequest();
    }

    public ConnectUtils param(String key, Object value){
        mParams.put(key,value);
        return this;
    }

    public ConnectUtils url(String url){
        this.mUrl = url;
        return this;
    }

    public ConnectUtils cache(boolean cache){
        // TODO
        this.cache = cache;
        return this;
    }

    public <T> void request(){
        request(null);
    }

    public <T> void request(final HttpCallBack<T> callback){
        if(mHttpRequest == null){
            mHttpRequest = mInitHttpRequest;
        }
        if(mHttpRequest == null){
            throw new NullPointerException("HttpRequest 是空，请配置");
        }
        if(mConfig != null && mConfig.platform != null){
            mParams.put("platform",mConfig.platform);
        }

        if(TextUtils.isEmpty(mUrl)){
            throw new NullPointerException("访问路径为空");
        }
        // 异常判断
        mHttpRequest.get(mContext,mUrl,mParams,callback,cache);
    }

    /*public  <T> void get(Context context, String url, Map<String, Object> params, final HttpCallBack<T> callback, final boolean cache) {
        mHttpRequest.get(context,url,params,callback,cache);
    }
    // 10几个参数以上
    public  <T> void get(Context context, String url, Map<String, Object> params,
                         final HttpCallBack<T> callback, final boolean cache,final boolean cookie,int recount) {
        mHttpRequest.get(context,url,params,callback,cache);
    }*/
}
